<template>
  <div class="pay-use">
    <el-form class="query-form" inline size="small" ref="queryForm">
      <el-form-item label="渠道" prop="unionid" class="big-query">
        <el-cascader
        v-model="queryParams.unionid"
        :options="channelOpts"
        :props="{ multiple: true,emitPath:false }"
        collapse-tags
        clearable
        filterable
        @change="init"></el-cascader>
            <!-- <select-check-box v-model="queryParams.unionid"
          style="width: 260px"
          :selOptions="channelOpts"
          checkAllLabel="全部渠道"
          filterable
          :props="{ value: 'channel_id', label: 'name' }"
          @change="init">
          <template #suffix="{item}">
            <span>（{{item.channel_id}}）</span>
          </template>
        </select-check-box> -->
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <version-select ref="versionSelect" :selOptions="versionOpts" isIntVer v-model="queryParams.version" @change="init"></version-select>
      </el-form-item>
      <el-form-item label="时间" prop="time_range">
        <el-date-picker v-model="queryParams.time_range" type="daterange" :clearable="false" value-format="yyyy-MM-dd" @change="init(true)">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" :loading="exportLoading" @click="onExport">导出</el-button>
      </el-form-item>
    </el-form>
    <div>
      <BarCharts v-loading="desktopLoading" :dataObj="xzdesktopData" titleText="桌面付费用户功能使用排行：" key="desktop"></BarCharts>
      <BarCharts v-loading="todoLoading" id="todo" :dataObj="xztodoData" titleText="小智ToDo付费用户功能使用排行" key="todo"></BarCharts>
      <BarCharts v-loading="sosopLoading" id="soso" :dataObj="xzsosoData" titleText="搜搜付费用户功能使用排行：" key="soso"></BarCharts>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getChartReport, getDashboardCharts, createExportTask, queryExportTask } from '@/api/report'
import { getChannelByAppId } from '@/api/system/channel'
import { getVersionTree } from '@/api'
import BarCharts from '@/components/Charts/bar-charts'
import { parseTime, downloadExportUrl } from '@/utils/index'
export default {
  name: 'PayUseReport',
  components: {
    BarCharts
  },
  data () {
    return {
      exportLoading: false,
      desktopLoading: false,
      todoLoading: false,
      sosopLoading: false,
      queryParams: {
        unionid: [],
        version: [],
        time_range: []
      },
      channelOpts: [],
      versionOpts: [],
      xzdesktopData: {
        xdata: [],
        ydata: []
      },
      xztodoData: {
        xdata: [],
        ydata: []
      },
      xzsosoData: {
        xdata: [],
        ydata: []
      }
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  },
  async created () {
    const d = new Date()
    d.setDate(d.getDate() - 1)
    const dateStr = parseTime(d, '{y}-{m}-{d}')
    this.queryParams.time_range = [dateStr, dateStr]
    await getDashboardCharts({ title: '桌面付费用户功能使用排行' }).then(res => {
      const data = res.data[0] || {}
      const metrics = data.metrics || []
      this.indicatorList = metrics.map(item => item.indicator)
    })
    await getDashboardCharts({ title: '小智ToDo付费用户功能使用排行' }).then(res => {
      const data = res.data[0] || {}
      const metrics = data.metrics || []
      this.indicatorTodoList = metrics.map(item => item.indicator)
    })
    await getDashboardCharts({ title: '搜搜付费用户功能使用排行' }).then(res => {
      const data = res.data[0] || {}
      const metrics = data.metrics || []
      this.indicatorSosoList = metrics.map(item => item.indicator)
    })
    this.getChannels()
    this.getVerLists()
    this.init()
  },
  methods: {
    init () {
      const params = this.getParams()
      this.getXzdesktopReport(params)
      this.getXztodoReport(params)
      this.getXzsosoReport(params)
    },
    getParams () {
      const params = {
        datasource: 18,
        granularity: 'pay_time'
        // time_grain_sqla: 'P1D'
      }
      const queryParams = this.queryParams
      const filters = []
      if (queryParams.time_range && queryParams.time_range.length) {
        params.time_range = queryParams.time_range[0] + 'T00:00:00 : ' + queryParams.time_range[1] + 'T23:59:59'
      }
      if (queryParams.unionid.length) {
        filters.push(`unionid in (${queryParams.unionid.join(',')})`)
      }
      if (queryParams.version.length) {
        filters.push(`version in (${queryParams.version.join(',')})`)
      }
      if (filters.length) {
        params.filters = filters.join(' and ')
      }
      return params
    },
    getXzdesktopReport (obj) {
      const params = Object.assign({
        indicator: this.indicatorList.join(',')
      }, obj)
      this.desktopLoading = true
      getChartReport(params).then(res => {
        this.xzdesktopData = this.formatCharts(res)
      }).finally(() => {
        this.desktopLoading = false
      })
    },
    getXztodoReport (obj) {
      const params = Object.assign({
        indicator: this.indicatorTodoList.join(',')
      }, obj)
      this.todoLoading = true
      getChartReport(params).then(res => {
        this.xztodoData = this.formatCharts(res)
      }).finally(() => {
        this.todoLoading = false
      })
    },
    getXzsosoReport (obj) {
      const params = Object.assign({
        indicator: this.indicatorSosoList.join(',')
      }, obj)
      this.sosopLoading = true
      getChartReport(params).then(res => {
        this.xzsosoData = this.formatCharts(res)
      }).finally(() => {
        this.sosopLoading = false
      })
    },
    formatCharts (res) {
      const obj = {
        xdata: [],
        ydata: []
      }
      if (Array.isArray(res.data[0].result)) {
        const ydata = []
        const result = res.data[0].result[0]
        const xdata = (result.colnames || []).filter(item => item !== '__timestamp')
        const list = result.data || []
        const data = list[0] || {}
        for (const item of xdata) {
          ydata.push(data[item] || 0)
        }
        obj.xdata = xdata
        obj.ydata = ydata
      }
      return obj
    },
    getChannels () {
      let list = this.permission_projectList.map(item => item.app_id)
      getChannelByAppId({ app_ids: list.join(',') }).then(res => {
        const channelList = res.data.list
        for (const item of this.permission_projectList) {
          item.label = item.name
          item.value = parseInt(item.app_id)
          const list = channelList.filter(item1 => item1.app_id === item.value)
          item.children = list.map(item => ({ label: `${item.name}(${item.channel_id})`, value: item.channel_id }))
        }
        this.channelOpts = this.permission_projectList
      })
    },

    getVerLists () {
      getVersionTree({ app_id: 22, is_test: false })
        .then(res => {
          let list = res.data || []
          this.versionOpts = list
        })
    },
    onExport () {
      this.exportLoading = true
      const filter = this.getParams()
      const params = {
        topic: 'fufeirank',
        filter: {
          '桌面': {
            indicator: this.indicatorList.join(','),
            ...filter
          },
          '小智ToD': {
            indicator: this.indicatorTodoList.join(','),
            ...filter
          },
          '搜搜': {
            indicator: this.indicatorSosoList.join(','),
            ...filter
          }
        }
      }
      createExportTask(params)
        .then(response => {
          const { task_id } = response.data || {}
          if (task_id) {
            this.queryExportTask(task_id, () => {
              this.exportLoading = false
            })
          } else {
            this.$message.error('导出订单任务创建失败')
            this.exportLoading = false
          }
        })
        .catch(e => {
          this.exportLoading = false
        })
    },
    /** 查询导出订单任务结果 */
    queryExportTask (task_id, func) {
      queryExportTask({ task_id })
        .then(response => {
          if (response.data?.status === 'finished') {
            downloadExportUrl(response.data.file_url)
            typeof func === 'function' && func(true)
          } else {
            setTimeout(() => {
              this.queryExportTask(task_id, func)
            }, 1000)
          }
        })
        .catch(() => {
          typeof func === 'function' && func(false)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
